﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.BLL.SMS;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;

namespace ZBJF.Warranty.BLL
{
    public partial class SendSmsVerificationCodeLogService
    {
        public string LoadLastVerificationCode(string phone)
        {
            var entity = LoadEntities(c => c.Phone == phone).OrderByDescending(c => c.SendTime).FirstOrDefault();
            return entity != null ? entity.VerificationCode : string.Empty;
        }

        /// <summary>
        /// 验证手机验证码是否有效(最后一条）
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <param name="validMinutes">有效分钟数</param>
        /// <returns></returns>
        public bool ValidatePhoneCode(string phone, string code, int validMinutes)
        {
            var entity = LoadEntities(c => c.Phone == phone && c.VerificationCode == code).OrderByDescending(c => c.SendTime).FirstOrDefault();
            if (entity != null && entity.SendTime.AddMinutes(validMinutes) > DateTime.Now)
                return true;
            return false;
        }

        /// <summary>
        /// 限制同一个手机号码一天发送短信的数量(默认五条）
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="limitSendCount"></param>
        /// <returns></returns>
        public bool PhoneSendCodeInLimitCount(string phone, int limitSendCount = int.MaxValue)
        {
            var expressionWhere = PredicateExtensions.True<SendSmsVerificationCodeLog>();
            var dtDay = DateTime.Now.ToString("yyyyMMdd");
            expressionWhere = expressionWhere.And(c => c.Phone == phone && (SqlFunctions.DateName("yyyy", c.SendTime) + SqlFunctions.DateName("MM", c.SendTime) + SqlFunctions.DateName("dd", c.SendTime)) == dtDay);
            var list = LoadEntities(expressionWhere).ToList();
            if (list.Count < limitSendCount)
                return true;
            return false;
        }

        public bool AddSendVerificationCode(string phone, string verificationCode)
        {
            return AddEntities(new SendSmsVerificationCodeLog
            {
                Phone = phone,
                VerificationCode = verificationCode,
                SendTime = DateTime.Now
            }).ID > 0;
            return false;
        }

        public bool SendSMS(string phone, string verificationCodeTemp, string sendMessages, ref string resultMsg, int limitCount = int.MaxValue)
        {
            if (string.IsNullOrEmpty(phone))
            {
                resultMsg = "手机号不能为空！";
                return false;
            }
            var verificationCodeTempEnum = VerificationCodeTemp.SMS_109355464;
            if (!Enum.TryParse(verificationCodeTemp, true, out verificationCodeTempEnum))
            {
                resultMsg = "验证模板参数错误！";
                return false;
            }
            if (PhoneSendCodeInLimitCount(phone,limitCount))
            {
                if (string.IsNullOrEmpty(sendMessages))
                    sendMessages = new ValidateCode().CreateValidateCode(6);

                var addFlag = AddSendVerificationCode(
                    phone,
                    sendMessages);
                if (addFlag)
                {
                    SMSHelper.VerificationCodeTemp = verificationCodeTempEnum.ToString();
                    SMSHelper.SendVerificationCodeSMS(phone, sendMessages, ref resultMsg);
                }
                else
                {
                    resultMsg = "添加发送短信记录失败，短信未发送！";
                }
            }
            else
            {
                resultMsg = string.Format("您的号码今日已超出短信发送数量限制（{0}条），请您明日再试！", 5);
            }
            if (resultMsg == "OK")
            {
                resultMsg = string.Format("验证码已发送至 {0}", phone);
                return true;
            }
            return false;
        }

    }
}
